import hashlib

from flask import Blueprint, redirect, render_template, request
from flask_login import current_user, login_required, logout_user

from com.cos import TenCos
from com.utils import upload_article_img, upload_avatar
from qingdeng.orms import ArticleORM, CategoryORM, UserORM

user_bp = Blueprint("user", __name__)


@user_bp.route("/account")
@login_required
def account_view():
    return redirect("/account/baseinfo")


@user_bp.route("/account/baseinfo")
@login_required
def base_info_view():
    return render_template("account/base_info.html")


@user_bp.route("/account/followed")
def follow_view():
    return render_template("account/followed.html")


@user_bp.route("/account/collection")
@login_required
def account_collection_view():
    # ?page=1&per_page=10
    page = request.args.get("page", type=int, default=1)
    per_page = request.args.get("per_page", type=int, default=10)

    user: UserORM = current_user
    paginate = user.collection_article_list.paginate(
        page=page, per_page=per_page, error_out=False
    )
    return render_template("account/collection.html", paginate=paginate)


@user_bp.route("/account/articles")
def articles_view():
    page = request.args.get("page", type=int, default=1)
    per_page = request.args.get("per_page", type=int, default=10)

    user: UserORM = current_user
    paginate = user.article_list.paginate(page=page, per_page=per_page, error_out=False)
    return render_template("account/articles.html", paginate=paginate)


@user_bp.route("/account/article_release")
def article_release_view():
    cate_list = CategoryORM.query.all()
    # 最新 是按照时间排序 不是一个类别
    cate_list.pop(0)
    return render_template("account/article_release.html", cate_list=cate_list)


@user_bp.route("/account/info", methods=["POST"])
def account_info():
    username = request.json.get("username")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    birthday = request.json.get("birthday")
    user: UserORM = current_user
    user.nick_name = username
    user.signature = signature
    user.gender = gender
    user.create_time = birthday
    user.save_to_db()
    return {"status": "success", "message": "修改信息成功"}


@user_bp.route("/account/password", methods=["POST"])
@login_required
def account_password():
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    user: UserORM = current_user
    if not user.check_password(old_password):
        return {"status": "fail", "message": "用户密码错误"}
    user.password = new_password
    user.save_to_db()
    logout_user()
    return {"status": "success", "message": "修改密码成功"}


@user_bp.route("/account/avatar", methods=["POST"])
@login_required
def account_avatar():
    avatar = request.files.get("file")

    filename = avatar.filename
    # 名字相同,内容不同
    suffix = filename.split(".")[-1]
    # name = uuid.uuid4().hex
    # 内容相同,名字不同 md5 摘要
    content = avatar.stream.read()  # 读取图片之后,就没有内容了
    name = hashlib.md5(content).hexdigest()  # 获取 md5 的值
    # print(name)
    filename = ".".join([name, suffix])
    flag, avatar_url = TenCos().save_user_pic(filename=filename, file=content)
    if flag != "ok":
        return {"status": "success", "message": "上传头像失败"}
    # avatar_url = upload_avatar(avatar)
    # 图书上传成功之后头像是否有修改 ?
    user: UserORM = current_user
    user.avatar_url = avatar_url
    user.save_to_db()
    return {"status": "success", "message": "上传头像成功", "avatar_url": avatar_url}


@user_bp.route("/account/article_img", methods=["POST"])
@login_required
def account_upload_article_img():
    avatar = request.files.get("file")

    avatar_url = upload_article_img(avatar)
    # 图书上传成功之后头像是否有修改 ?
    user: UserORM = current_user
    user.avatar_url = avatar_url
    user.save_to_db()
    return {"status": "success", "message": "上传文章图片成功", "avatar_url": avatar_url}


@user_bp.route("/user/posts_release", methods=["POST"])
def user_posts_release_view():
    title = request.json.get("title")
    category_id = request.json.get("category_id")
    digest = request.json.get("digest")
    image_url = request.json.get("image_url")
    content = request.json.get("content")

    article: ArticleORM = ArticleORM()
    article.title = title
    article.source = "个人-{}".format(current_user.nick_name)
    article.user_id = current_user.id
    article.category_id = category_id
    article.digest = digest
    article.index_image_url = image_url
    article.content = content
    article.save_to_db()
    return {"status": "success", "message": "发布文章成功"}
